package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.service.IAlertRuleService;
import com.zzyl.system.mapper.SysUserMapper;
import com.zzyl.system.mapper.SysUserRoleMapper;
import com.zzyl.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.language.bm.Rule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 报警规则Service业务层处理
 *
 * @author elina
 * @date 2025-10-17
 */
@Service
@Slf4j
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService {
    @Autowired
    private AlertRuleMapper alertRuleMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private IAlertDataService alertDataService;

    /**
     * 查询报警规则
     *
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id) {
        return alertRuleMapper.selectById(id);
    }

    /**
     * 查询报警规则列表
     *
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule) {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule) {
        return alertRuleMapper.insert(alertRule);
    }

    /**
     * 修改报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule) {
        return alertRuleMapper.updateById(alertRule);
    }

    /**
     * 批量删除报警规则
     *
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids) {
        return alertRuleMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 报警规则过滤
     */
    @Override
    public void alterFilter() {
        // 查询所有报警规则
        Long count = lambdaQuery()
                .eq(AlertRule::getStatus, 1)
                .count();
        if (count < 0) {
            log.info("当前没有设置过滤规则！");
            return;
        }
        List<AlertRule> alterRules = lambdaQuery().eq(AlertRule::getStatus, 1).list();
        // 查询所有设备上报的数据
        List<Object> dataList = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);
        if (CollUtil.isEmpty(dataList)) {
            log.info("当前没有设备上报数据！");
            return;
        }
        // 解析上报的数据
        ArrayList<DeviceData> deviceData = new ArrayList<>();
        dataList.forEach(data -> {
                    deviceData.addAll(JSONUtil.toList(data.toString(), DeviceData.class));
                }
        );

        // 获取报警规则，进行匹配
        // 遍历每个设备上报的数据的物模型
        deviceData.forEach(this::alterFilter);
    }

    /**
     * 报警规则过滤
     *
     * @param deviceData 设备上报的数据
     */
    private void alterFilter(DeviceData deviceData) {
        // 遍历所有设备上报数据
        if (ObjectUtil.isEmpty(deviceData)) {
            log.info("当前设备数据为空！");
            return;
        }
        // 检验上报时间是否小于1分
        LocalDateTime alarmTime = deviceData.getAlarmTime();
        long diff = LocalDateTimeUtil.between(alarmTime, LocalDateTime.now(), ChronoUnit.SECONDS);
        if (diff > 60) {
            log.info("当前上报数据已过期！");
            return;
        }
        // 准备对应报警规则数据
        // 查询当前设备的报警规则
        List<AlertRule> currentDeviceAlertRule = lambdaQuery().eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getIotId, deviceData.getIotId())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getStatus, 1)
                .list();
        // 查询所有设备的报警规则
        List<AlertRule> allDeviceAlertRule = lambdaQuery().eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getIotId, -1)
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getStatus, 1)
                .list();
        if (CollUtil.isEmpty(currentDeviceAlertRule) && CollUtil.isEmpty(allDeviceAlertRule)) {
            log.info("当前设备没有设置报警规则！");
            return;
        }
        // 合并报警规则
        Collection<AlertRule> alertRules = CollUtil.addAll(currentDeviceAlertRule, allDeviceAlertRule);
        // 按照给出的规则和数据进行过滤
        alertRules.forEach(ruler-> deviceDataAlarmHandler(ruler, deviceData));

    }

    /**
     * 规则校验
     * @param ruler
     * @param deviceData
     */
    private void deviceDataAlarmHandler(AlertRule ruler, DeviceData deviceData) {
        // 第一层校验：判断上报时间是否在生效时间内
        // 获取时间范围
        String[] split = ruler.getAlertEffectivePeriod().split("~");
        LocalDateTime startTime = LocalDateTimeUtil.parse(split[0]);
        LocalDateTime endTime = LocalDateTimeUtil.parse(split[1]);
        // 获取上报时间
        LocalDateTime alarmTime = deviceData.getAlarmTime();
        if (alarmTime.isBefore(startTime) || alarmTime.isAfter(endTime)) {
            log.info("当前数据不在生效时间段内！");
            return;
        }
        // 第二层校验：检验数据是否达到阈值
        // 拼接 redis 报警次数 key
        String alertCountKey = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX
                + ruler.getId() + ":" + deviceData.getIotId() + ":" + deviceData.getFunctionId();
        // 检验数据是否达到阈值
        Double value = ruler.getValue();
        String operator = ruler.getOperator();
        Double v = Double.valueOf(deviceData.getDataValue());
        // 获取比较结果
        int compare = Double.compare(v, value);
        // 没有达到阈值
        if (compare < 0 && "<".equals(operator) || compare >= 0 && ">=".equals(operator)) {
            log.info("当前数据没有达到阈值！");
            // 删除redis报警次数
            redisTemplate.delete(alertCountKey);
            return;
        }
        // 第三层校验判断是否在沉默周期内
        String alertSilentKey = CacheConstants.ALERT_SILENT_PREFIX + ruler.getId() + ":" + deviceData.getIotId() + ":" + deviceData.getFunctionId();
        if (redisTemplate.hasKey(alertSilentKey)) {
            log.info("当前数据在沉默周期中！");
            return;
        }
        // 第四层校验：检验持续周期
        // redis 中获取报警次数
        String alertCountStr = redisTemplate.opsForValue().get(alertCountKey);
        int alertCount = StrUtil.isEmpty(alertCountStr) ? 1 : Integer.parseInt(alertCountStr) + 1;
        // 判断报警次数是否达到持续周期
        if (alertCount != ruler.getDuration()) {
            log.info("当前数据未达到持续周期！");
            redisTemplate.opsForValue().set(alertCountKey, String.valueOf(alertCount));
            return;
        }
        // 检验全部通过，当前数据触发报警
        // 删除redis报警次数
        redisTemplate.delete(alertCountKey);
        // 添加redis沉默周期
        redisTemplate.opsForValue().set(alertSilentKey, "1", ruler.getAlertSilentPeriod(), TimeUnit.MINUTES);

        List<Long> userIds = null;
        // 判断是否是老人数据
        if (ruler.getAlertDataType() == 0) {
            // 判断是否是固定设备
            if (deviceData.getLocationType().equals(0)) {
                // 通过老人查询护理员
                userIds = deviceMapper.selectNursingIdsByIotIdWithElder(deviceData.getIotId());
            } else if (deviceData.getLocationType().equals(1) && deviceData.getPhysicalLocationType().equals(2) ){
                // 通过床位查询老人，再查询护理员
                userIds = deviceMapper.selectNursingIdsByIotIdWithBed(deviceData.getIotId());
            }
        } else {
            // 设备报警，查询维修员
            userIds = sysUserRoleMapper.selectUserIdByRoleName("维修工");
        }

        // 查询超级管理员
        userIds.addAll(sysUserRoleMapper.selectUserIdByRoleName("超级管理员"));

        // 对用户信息进行去重
        userIds = CollUtil.distinct(userIds);

        // 批量保存报警信息
        //保存报警数据
        insertAlertData(userIds, deviceData, ruler);

    }

    /**
     * 保存报警信息
     * @param userIds
     * @param deviceData
     * @param ruler
     */
    private void insertAlertData(List<Long> userIds, DeviceData deviceData, AlertRule ruler) {

        List<AlertData> alertDataList = userIds.stream().map(userId -> {
            AlertData alertData = BeanUtil.toBean(deviceData, AlertData.class);
            alertData.setId(null);
            alertData.setAlertRuleId(ruler.getId());
            alertData.setType(ruler.getAlertDataType());
            alertData.setStatus(0);
            alertData.setUserId(userId);
            String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", ruler.getFunctionName(), ruler.getOperator(), ruler.getValue(), ruler.getDuration());
            alertData.setAlertReason(alertReason);
            return alertData;
        }).collect(Collectors.toList());

        //批量保存报警数据
        alertDataService.saveBatch(alertDataList);
    }

    /**
     * 删除报警规则信息
     *
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id) {
        return alertRuleMapper.deleteById(id);
    }
}
